package charlie.shop.warehouse;

import com.charlie.beans.Product;
import com.charlie.sessions.ProductFacadeLocal;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Create new products servlet
 * 
 * @author Gleb
 */
@WebServlet(name = "addProduct", urlPatterns = {"/warehouse/addProduct"})
public class addProduct extends HttpServlet {

    @EJB
    private ProductFacadeLocal productFacade;

    /**
     * Get creation parameters and create new product
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        if (request.getParameter("productName") != null && !request.getParameter("productName").equals("") && request.getParameter("cost") != null && !request.getParameter("cost").equals("")) {
            Product product = new Product();
            product.setName(request.getParameter("productName"));
            product.setCost(Integer.parseInt(request.getParameter("cost")));
            product.setDescription(request.getParameter("description"));
            product.setImage(request.getParameter("upFile"));
            product.setStatus(1);
            productFacade.create(product);
            response.sendRedirect(request.getContextPath() + "/warehouse/products");
            return;
        }
        request.getRequestDispatcher("/warehouse/addProduct.jsp").forward(request, response);

    }

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }   
}
